import React, { Component } from 'react'
import { Form, Icon, Input, Button } from 'antd'
import { Redirect } from 'react-router-dom'


import storageUtils from "../../utils/storageUtils"

import './login.less'
import logo from '../../components/left-nav/logo.jpg'

// 登录的路由组件
class Login extends Component {
  handleSubmit = (event) => {
    event.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      // 校验成功
      if(!err) {
        const { username } = values
        storageUtils.saveUser({username})
        this.props.history.replace('/screen')
      }
    })
  }

  render() {

    const user = storageUtils.getUser()?.username
    if(user) {
      return <Redirect to="/" />
    }

    // 得到具有强大功能的form对象
    const form = this.props.form
    const { getFieldDecorator } = form
    return (
      <div className="login">
        <header className="login-header">
          <img src={logo} alt="logo" />
          <h1>伯乐捞: 后台管理系统</h1>
        </header>
        <section className="login-content">
          <h2>用户登录</h2>
          <Form onSubmit={this.handleSubmit} className="login-form">
            <Form.Item>
              {
                getFieldDecorator('username', { 
                  rules: [{required: true, whitespace: true, message: '请输入用户名'}],
                  initialValue: 'admin'
                })(
                  <Input
                    prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    placeholder="Username" 
                    autoComplete="off"
                  />,
                )
              }
            </Form.Item>
            <Form.Item>
              {
                getFieldDecorator('password', {
                  rules: [
                    {required: true, message: '请输入密码'}
                  ]
                })(
                  <Input
                    prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                    type="password"
                    placeholder="password"
                    autoComplete="off"
                  />,
                )
              }
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                Log in
              </Button>
            </Form.Item>
          </Form>
        </section>
      </div>
    )
  }
}

const WrapLogin = Form.create()(Login)
export default WrapLogin
